package interceptor

import (
	"context"
	"fmt"
	"github.com/zeromicro/go-zero/core/logx"
	"go-exp/common/constantkey"
	"go-exp/pkg/ctxdata"
	"google.golang.org/grpc"
	"google.golang.org/grpc/metadata"
	"strconv"
)

// RpcAuthInterceptor 是 RPC 客户端的认证拦截器
func RpcAuthInterceptor() grpc.UnaryClientInterceptor {
	return func(ctx context.Context, method string, req, reply interface{}, cc *grpc.ClientConn, invoker grpc.UnaryInvoker, opts ...grpc.CallOption) error {
		// 从当前 context 中获取认证信息
		claims, ok := ctxdata.GetAuthClaims(ctx)
		if ok && claims != nil {
			md := metadata.Pairs(
				constantkey.UserIDKey, fmt.Sprintf("%d", claims.UserID),
				//constantkey.UserNameKey, claims.UserName,
				constantkey.RoleKey, claims.Role,
			)
			ctx = metadata.NewOutgoingContext(ctx, md)
		}
		return invoker(ctx, method, req, reply, cc, opts...)
	}
}

func ServerAuthInterceptor() grpc.UnaryServerInterceptor {
	return func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (resp interface{}, err error) {
		logx.WithContext(ctx).Infof("gRPC Server Interceptor: %s", info.FullMethod)

		md, ok := metadata.FromIncomingContext(ctx)
		if !ok {
			logx.WithContext(ctx).Infof("RPC call missing metadata")
			return handler(ctx, req)
		}

		userIDs := md.Get(constantkey.UserIDKey)
		if len(userIDs) == 0 {
			logx.WithContext(ctx).Infof("UserID not found in gRPC metadata (key: %s)", "user-id")
			return handler(ctx, req)
		}
		userID := userIDs[0]
		if userID == "" {
			logx.WithContext(ctx).Infof("UserID is empty in gRPC metadata")
			return handler(ctx, req)
		}

		logx.WithContext(ctx).Infof("Authenticated UserID from gRPC metadata: %s", userID)

		atom, _ := strconv.Atoi(userID)
		// 将 UserID 存入 Context，供后续 Logic 使用
		newCtx := ctxdata.SetAuthClaims(ctx, &ctxdata.AuthClaims{
			UserID: int64(atom),
		})
		return handler(newCtx, req)
	}
}
